//
//  DataBaseHandle.m
//  UI19_HomeWork_wangyi
//
//  Created by dllo on 16/1/19.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "DataBaseHandle.h"
#import <sqlite3.h>

@implementation DataBaseHandle

/** 创建单例数据库 */
+ (instancetype)shareDataBaseHandle {

    static DataBaseHandle *dataBase = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataBase = [DataBaseHandle new];
    });
    return dataBase;
}

sqlite3 *db;
- (void)open:(NSString *)file {
    if (db) {
        NSLog(@"数据库已开启!!!");
        return;
    }
    int result = sqlite3_open(file.UTF8String, &db);
    if (result == SQLITE_OK) {
        NSLog(@"数据库打开成功!");
    }else {
        NSLog(@"数据库打开失败!,code = %d", result);
    }
}

- (void)closeDB {
    int result = sqlite3_close(db);
    if (result == SQLITE_OK) {
        NSLog(@"数据库关闭成功");
        db = nil;
    }else {
        NSLog(@"数据库关闭失败.code:%d", result);
    }
}
//增/删/改
- (void)updateSQL:(NSString *)SQL {
    int result = sqlite3_exec(db, SQL.UTF8String, nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"成功!");
    }else {
        NSLog(@"失败!.code:%d", result);
    }
}

- (NSArray *)selectAllWithList:(NSString *)list AndListNumber:(NSInteger)num {
    NSMutableArray *arr = [NSMutableArray array];
    // SQL语句
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM %@", list];
    //声明一个stmt对象(结构体)
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(db, selectSQL.UTF8String, -1, &stmt, nil);
    if (result == SQLITE_OK) {
        // 每行都执行查询语句
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //如果查询条件匹配.通过sqlite3_column函数簇 取出值.
            NSMutableArray *tempArr = [[NSMutableArray alloc] init];
            for (int i = 0 ; i < num; i++) {
                const unsigned char *str = sqlite3_column_text(stmt, i);
                [tempArr addObject:[NSString stringWithUTF8String:(const char *)str]];
            }
            [arr addObject:tempArr];
        }        
        //销毁对象.
        sqlite3_finalize(stmt);
    }else {
        NSLog(@"不能正常查询.code:%d", result);
        //销毁对象.
        sqlite3_finalize(stmt);
    }
    return arr;
}
@end
